import { LitElement, css, html } from "lit";
import { customElement, property } from "lit/decorators.js";
import axios from "axios";

/**
 * An example element.
 *
 * @slot - This element has a slot
 * @csspart button - The button
 */
@customElement("page-frame")
export class MyElement extends LitElement {
  /**
   * Copy for the read the docs hint.
   */
  @property()
  docsHint = "Click on the Vite and Lit logos to learn more";

  /**
   * The number of times the button has been clicked.
   */
  @property({ type: Number })
  count = 0;

  userLogined: User;

  constructor() {
    super();
    axios.get("/admin/v1/user/logined").then((res) => {
      this.userLogined = res.data;
    });
  }

  submitLogin(e: Event) {
    e.preventDefault();
    const form = e.target as HTMLFormElement;
    const username = form.username.value;
    const password = form.password.value;
    axios
      .post("/admin/v1/user/login", { username, password })
      .then((res) => {
        this.userLogined = res.data;
      })
      .catch((err) => {
        console.error(err);
      });
  }

  render() {
    if (this.userLogined) {
      return this.renderAdminPage();
    } else {
      return this.renderLogin();
    }
  }

  renderLogin() {
    return html`
      <div class="card">
        <h1>登录涂酱OCR系统</h1>
        <form>
          <label for="username">用户名</label>
          <input type="text" id="username" name="username" />
          <label for="password">密码</label>
          <input type="password" id="password" name="password" />
          <button type="submit" @click=${this.submitLogin.bind(this)} >登录</button>
        </form>
      </div>
    `;
  }

  renderAdminPage() {
    return html` <admin-page></admin-page> `;
  }

  private _onClick() {
    this.count++;
  }

  static styles = css`
    :host {
      display: flex;
      place-content: center;
      padding: 25px 25px 55px 25px;
      width: 400px;
      border-radius: 8px;
      color: var(--page-frame-text-color, #000);
      background-color: var(--page-frame-background-color, #fff);
    }

    h1 {
      margin-bottom: 16px;
      font-weight: lighter;
    }

    form {
      display: flex;
      flex-direction: column;
    }
    label {
      margin-bottom: 8px;
    }
    input {
      margin-bottom: 16px;
      padding: 8px;
    }
    button {
      padding: 8px;
      background-color: #0078d4;
      color: white;
      border: none;
    }
  `;
}

declare global {
  interface HTMLElementTagNameMap {
    "my-element": MyElement;
  }
}
